package com.yiyuan.app.mqtt;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.mqtt.server.callback.StatusListener;
import com.alibaba.mqtt.server.model.StatusNotice;
import com.alibaba.mqtt.server.model.StatusType;
import com.yiyuan.app.dao.GConfDeviceDAO;
import com.yiyuan.app.dao.GDeviceStatusDAO;
import com.yiyuan.app.entity.po.GDeviceStatusPO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class ClientStatusListener implements StatusListener {

    private final GConfDeviceDAO gConfDeviceDAO;
    private final GDeviceStatusDAO gDeviceStatusDAO;

    @Override
    public void process(StatusNotice statusNotice) {
        String clientId = statusNotice.getClientId();
        if (clientId.endsWith("_APP") || clientId.endsWith("_web") || clientId.endsWith("_device") || clientId.endsWith("_service_io") || clientId.endsWith("_io_backed")) {
            return;
        }
        StatusType statusType = statusNotice.getStatusType();
        String[] split = clientId.split("@@@");
        String deviceNo = split[1];
        log.info("终端设备" + deviceNo + " |" + statusType.name() + "通知，{}", JSONObject.toJSONString(statusNotice));
        if (statusType.name().equals(StatusType.ONLINE.name())) {
            GDeviceStatusPO po = new GDeviceStatusPO();
            po.setChannelId(statusNotice.getChannelId());
            po.setClientId(deviceNo);
            try {
                gDeviceStatusDAO.save(po);
            } catch (Exception e) {
                log.error("新增设备状态异常，{}", e);
            }
        } else {
            gDeviceStatusDAO.delete(statusNotice.getChannelId(), deviceNo);
        }
        List<GDeviceStatusPO> list = gDeviceStatusDAO.findList(GDeviceStatusPO::getClientId, deviceNo);
        gConfDeviceDAO.updateDeviceStatus(deviceNo, CollectionUtils.isNotEmpty(list));
    }
}
